package com.openlogic.common.core.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Row.MissingCellPolicy;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.UploadedFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.openlogic.common.core.constants.HttpConstant;
import com.openlogic.common.core.exception.ServiceException;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;

/**
 * Excel相关处理
 * @author xm
 */
public class ExcelUtil {
    
    private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);

	private static final String XLS = "xls";

	private static final String XLSX = "xlsx";

	private static final String SPLIT = ".";

    /**
     * 导出 Excel
     * @param list 数据
     * @return
     */
    public static <T> void export(List<T> list,String fileName) {
        if(list.isEmpty()) {
            throw new ServiceException("导出数据为空");
        }
//        Context ctx = ContextUtil.getContext();
//        ctx.contentType(HttpConstant.CONTENT_TYPE_FORM);
        ExportParams exportParams = new ExportParams();
        exportParams.setType(ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, list.get(0).getClass(), list);
        try {
			responseWorkbook(workbook,fileName);
            //workbook.write(ctx.outputStream());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
	/**
	 * 描述：创建WorkBoot
	 * @Title: getWorkbook
	 * @param file
	 * @return
	 * @author weiyongpeng
	 * @param dbPath
	 * @date 2024年11月26日 下午3:49:25
	 */
	public static Workbook getWorkbook(UploadedFile file, String dbPath) {
		Workbook workbook = null;
		try {
			// 获取Excel后缀名
			String fileName = file.getName();
			if (StringUtils.isEmpty(fileName) || fileName.lastIndexOf(SPLIT) < 0) {
				log.warn("解析Excel失败，因为获取到的Excel文件名非法！");
				return null;
			}
			String fileType = fileName.substring(fileName.lastIndexOf(SPLIT) + 1, fileName.length());
			// 获取Excel工作簿
			if (fileType.equalsIgnoreCase(XLS)) {
				workbook = new HSSFWorkbook(new FileInputStream(new File(dbPath)));
			} else if (fileType.equalsIgnoreCase(XLSX)) {
				workbook = new XSSFWorkbook(new FileInputStream(new File(dbPath)));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return workbook;
	}

	/**
	 * 描述：获取sheet的column标题
	 * @Title: getSheetTitles
	 * @param workbook
	 * @return
	 * @author weiyongpeng
	 * @date 2024年11月26日 下午3:50:04
	 */
	public static List<Cell> getSheetTitles(Workbook workbook) {
		// 拿第一个sheet表
		Sheet sheet = workbook.getSheetAt(0);
		// 校验sheet是否合法
		if (Objects.isNull(sheet)) {
			return null;
		}
		// 获取第一行数据（假如第一行就是列名）
		Row sheetTitleRow = sheet.getRow(sheet.getFirstRowNum());
		// 取出最后一列
		short lastCellNum = Optional.ofNullable(sheetTitleRow.getLastCellNum()).isPresent()
				? sheetTitleRow.getLastCellNum()
				: 0;
		List<Cell> sheetTitleList = new LinkedList<>();
		for (int i = 0; i < lastCellNum; i++) {
			// 取出每一列的名
			// String cellValue = sheetTitleRow.getCell(i).getStringCellValue();
			// String cellType = sheetTitleRow.getCell(i).getCellType().name();
			Cell cell = sheetTitleRow.getCell(i, MissingCellPolicy.RETURN_NULL_AND_BLANK);
			sheetTitleList.add(cell);
		}
		return sheetTitleList;
	}

	/**
	 * 描述：获取sheet名称
	 * @Title: getSheetName
	 * @param workbook
	 * @return
	 * @author weiyongpeng
	 * @date 2024年11月26日 下午4:00:06
	 */
	public static String getSheetName(Workbook workbook) {
		// 拿第一个sheet表
		Sheet sheet = workbook.getSheetAt(0);
		// 校验sheet是否合法
		if (Objects.isNull(sheet)) {
			return null;
		}
		// 获取第一行数据（假如第一行就是列名）
		String name = sheet.getSheetName();
		return name;
	}



	/**
	 * 导出 Excel
	 *
	 * @param workbook
	 * @param fileName
	 */
	private static void responseWorkbook(Workbook workbook, String fileName) {
		try {
			Context context = Context.current();
			context.headerSet("Content-disposition", "attachment;" + "filename*=utf-8''" + URLEncoder.encode(fileName, "UTF-8"));
			context.contentType(HttpConstant.CONTENT_TYPE_FORM);
			workbook.write(context.outputStream());
			workbook.close();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}
